package com.learn.hd.interview.thread;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhanghaidong
 * @version v1.0
 * @description  CountDownLatch 倒计时器
 * @date 2019/6/27
 */
public class CountDownLatchDemo implements Runnable {

    static final CountDownLatch latch = new CountDownLatch(10);

    @Override
    public void run() {
        // 模拟检查任务
        try {
            Thread.sleep(new Random().nextInt(10) * 1000);
            System.out.println("check complete");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //计数减一
            latch.countDown();
        }
    }

    /**
     * 上述代码中我们先生成了一个CountDownLatch实例。计数数量为10，这表示需要有10个线程来完成任务，等待在CountDownLatch上的线程才能继续执行。
     * latch.countDown();方法作用是通知CountDownLatch有一个线程已经准备完毕，倒计数器可以减一了。
     * latch.await()方法要求主线程等待所有10个检查任务全部准备好才一起并行执行。
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {

        CountDownLatchDemo demo = new CountDownLatchDemo();
        ExecutorService exec = Executors.newFixedThreadPool(10);
        for (int i=0; i<10; i++){
            exec.submit(demo);
        }

        // 等待检查
        latch.await();

        // 发射火箭
        System.out.println("Fire!");
        // 关闭线程池
        exec.shutdown();
    }
}
